﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DoKnow.CloudEdu.CMS.Host.Models;
using DoKnow.CloudEdu.Common.Consts;
using DoKnow.CloudEdu.DataContract.Model.Base;
using DoKnow.Common.Utility;
using Newtonsoft.Json;

namespace DoKnow.CloudEdu.CMS.Host.Controllers
{
    public class HomeController : BaseController
    {

        //
        // GET: /Home/

        public ActionResult Index()
        {
            return View();
        }
        public ActionResult Login()
        {
            //var m = CurCache.BSModuleFull;
            return View();
        }
        [HttpPost]
        public ActionResult Login(string mobile, string password)
        {
            if (string.IsNullOrWhiteSpace(mobile) || string.IsNullOrWhiteSpace(password))
            {
                ViewBag.ErrMsg = "用户名或密码不能为空";
                //return View();
                return PartialView("Login", "Home");
            }
            string userKey = Guid.NewGuid().ToString();
            UserData user = HttpHelper.Post<UserData>(Server + ServicePath.UserRead,
                JsonConvert.SerializeObject(
                new
                {
                    ActionName = "LoginWrapper", 
                      Pars = 
                      new {
                          User = new { Mobile = mobile, Password = password } 
                          } 
                    }));
            if (null == user)
            {
                ViewBag.ErrMsg = "用户名或者密码错误";
                //return View();
                return PartialView("Login", "Home");
            }
            //session related with cookie key
            AddSession<UserData>(userKey, user);
            //Create a cookie, and then add the encrypted ticket to the cookie as data.
            HttpCookie authCookie = new HttpCookie(CookiesKey.LoginToken, userKey);
            authCookie.Expires = DateTime.Now.AddMinutes(60);
            //Add the cookie to the outgoing cookies collection.
            Response.Cookies.Add(authCookie);
            return RedirectToAction("Index", "Home");
        }
        public ActionResult Logout()
        {
            Response.Cookies[CookiesKey.LoginToken].Expires = DateTime.Now.AddDays(-1);
            Session.Remove(LoginToken);
            return RedirectToAction("Login");
        }
    }
}
